<template>
  <el-drawer class="role-list-page" title="应用角色管理" size="1200" direction="ltr" v-model="visible" destroy-on-close @closed="$emit('closed')">
    <el-container style="border-top: solid 1px #e4e7ed;border-bottom: solid 1px #e4e7ed;margin: 0px 15px;">
      <el-aside width="220px">
        <el-container>
          <el-header>
            <el-input placeholder="输入关键字进行过滤" v-model="roleFilterText" clearable></el-input>
          </el-header>
          <el-main class="nopadding" style="background: #fff;padding-top: 10px;">
            <template v-if="roleList.length>0">
              <el-tree ref="roles" class="menu" node-key="id" default-expand-all :data="roleList" :highlight-current="true" :expand-on-click-node="false" :filter-node-method="roleFilterNode" @node-click="roleClick" v-loading="loading.role">
                <template #default="{node, data}">
                  <span class="custom-tree-node" :class="data.status=='1'?'disabled':''">
                    <span class="label">{{ data.groupName }}</span>
                    <span class="code">{{ data.groupId }}</span>
                    <span class="do" v-if="data.id != ''">
                      <el-button-group>
                        <el-button icon="el-icon-edit" size="small" @click.stop="roleModify(node, data)"></el-button>
                        <el-button icon="el-icon-delete" size="small" @click.stop="roleDelete(node, data)"></el-button>
                      </el-button-group>
                    </span>
                  </span>
                </template>
              </el-tree>
            </template>
            <template v-else>
              <el-empty description="暂无应用角色信息" :image-size="100" style="margin-top: 100px"></el-empty>
            </template>
          </el-main>
          <el-footer style="height:51px;text-align: center;">
            <el-button-group style="width: 100%">
              <el-button type="primary" size="small" icon="el-icon-plus" @click="addRole" style="width: 100%">添加应用角色</el-button>
            </el-button-group>
          </el-footer>
        </el-container>
      </el-aside>
      <el-container>
        <el-header>
          <div class="left-panel">
            <el-button type="primary" icon="el-icon-plus" @click="selectUser" :disabled="roleId==null"></el-button>
            <el-button type="danger" plain icon="el-icon-delete" v-if="selection.length > 0" @click="batchMemberDel"></el-button>
          </div>
          <div class="right-panel">
            <div class="right-panel-search">
              <el-input ref="searchInput" v-model="search.keyword" minlength="1" maxlength="20" placeholder="账号/姓名/手机" clearable></el-input>
              <el-button type="primary" icon="el-icon-search" @click="memberSearch"></el-button>
            </div>
          </div>
        </el-header>
        <el-main class="nopadding" v-loading="loading.users">
          <jdTable ref="table" :data="usersList" size="large" @selection-change="selectionChange" :params="params" stripe hideSetting remoteSort remoteFilter>
            <el-table-column type="selection"></el-table-column>
            <el-table-column label="账号" prop="userName" width="150" fixed="left"></el-table-column>  
            <el-table-column label="姓名" prop="nickName" width="150" fixed="left"></el-table-column>
            <el-table-column label="手机号" prop="phone" width="150"></el-table-column>                 
            <el-table-column label="性别" prop="sex" align="center" width="150">
              <template #default="scope">
                <DictTag :options="dict.sex" :value="scope.row.sex"></DictTag>
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="deptName" min-width="200"></el-table-column>
            <el-table-column label="状态" prop="status" width="150" align="center">
              <template #default="scope">
                <DictTag :options="dict.status" :value="scope.row.status"></DictTag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="150">
              <template #default="scope">
                <el-button-group>
                  <el-popconfirm title="确定要删除吗？" @confirm="removeMember(scope.row, scope.$index)">
                    <template #reference>
                      <el-button text type="primary" class="button">删除</el-button>
                    </template>
                  </el-popconfirm>
                </el-button-group>
              </template>
            </el-table-column>
          </jdTable>
        </el-main>
      </el-container>
    </el-container>
  </el-drawer>
  <select-dialog v-if="dialog.select" ref="selectDialog" @success="handleSaveSuccess" @closed="dialog.select = false"></select-dialog>
</template>

<script>
import selectDialog from "@/views/system/member/select.vue"
import PinYin from "js-pinyin"
import Sortable from "sortablejs"
export default {
  name: "roleList",
  components: {
    selectDialog
  },
  data() {
    return {
      visible: false,
      selection: [],
      showRoleDetail: false,
      loading: {
        role: false,
        users: true,
      },
      dialog: {
        select: false
      },
      dict:{
        sex:[],
        status:[],
      },
      params: {},
      selection: [],
      search: {
        keyword: null
      },
      roleId: null,
      roleList: [],
      roleFilterText: '',
      usersList: [],
      appId:null,
    }
  },
  watch: {
    roleFilterText(val) {
      this.$refs.roles.filter(val);
    }
  },
  methods: {
    // 显示
    open(appId) {
      this.visible = true;
      this.search.keyword = '';
      this.appId = appId;
      // 加载角色列表
      this.getRoles();
      // 加载配置字典
      this.getDict();
    },
    // 字典获取
    async getDict() {
      this.dict = {
        sex: await this.Dict.get("sys_user_sex"),
        status: await this.Dict.get("sys_normal_disable")
      }
    },
    // 加载角色列表
    async getRoles() {
      this.loading.role = true;
      var res = await this.$API.app.appStore.listAppRoleList.get({pageSize: 100, "appId": this.appId});
      if (res.code == 200) {
        this.roleList = res.data.rows;

        if (this.roleList.length > 0) {
          this.roleId = this.roleList[0].id;
          this.$nextTick(() => {
            this.$refs.roles.setCurrentKey(this.roleId);
            this.getUsers(this.roleId);
          });
        }
        this.loading.role = false;
        this.loading.users = false;
      }
    },
    // 加载用户列表
    async getUsers(groupId){
      this.loading.users = true;
      var params = {
        groupId: groupId,
        searchValue: this.search.keyword
      }
      var res = await this.$API.app.appStore.listRoleUserList.get(params);
      if (res.code == 200){
        this.usersList = res.data.rows;
        this.loading.users = false;
      }
      this.loading.users = false;
    },
    //树过滤
    roleFilterNode(value, data){
      if (!value) return true;
      var targetText = data.groupName;
      return targetText.indexOf(value) !== -1;
    },
    // 角色树点击事件
    roleClick(data) {
      this.search.keyword = '';
      this.roleId = data.id;
      // 加载用户列表
      this.getUsers(data.id);
    },
    // 添加角色
    addRole(){
      this.$prompt('角色名称', '新建角色', {
        inputPlaceholder: '请输入一个方便识别的角色名称',
        inputPattern: /\S/,
        inputErrorMessage: '角色名称不能为空'
      })
      .then(async ({ value }) => {
        // 获取拼音首字母
        PinYin.setOptions({ checkPolyphone: false, charCase: 0 })
        var roleKey = PinYin.getCamelChars(value)

        var data = {
          groupName: value,
          appId: this.appId
        }
        var res = await this.$API.app.appStore.addAppRole.post(data);
        if(res.code == 200){
          this.$refs.roles.append({
            groupId: res.data,
            groupName: data.groupName
          });
          this.$message.success("操作成功")
        }else{
          this.$alert(res.msg, "提示", {type: 'error'})
        }
      });
    },
    // 编辑角色
    async roleModify(node, data){
      var id = data.id;
      this.$prompt('角色名称', '编辑角色', {
        inputPlaceholder: '请输入一个方便识别的角色名称',
        inputPattern: /\S/,
        inputErrorMessage: '角色名称不能为空',
        inputValue: data.groupName
      })
      .then(async ({ value }) => {
        // 获取拼音首字母
        PinYin.setOptions({ checkPolyphone: false, charCase: 0 })
        var roleKey = PinYin.getCamelChars(value)

        var data = {
          id: id,
          groupName: value
        }
        var res = await this.$API.app.appStore.updateAppRole.put(data);
        if(res.code == 200){
          let updateNode = this.$refs.roles.getNode(node);
          if (updateNode) {
            updateNode.data.groupName = value
          }
          this.$message.success("操作成功")
        }else{
          this.$alert(res.msg, "提示", {type: 'error'})
        }
      });
    },
    // 删除角色
    async roleDelete(node, data){
      var res = await this.$API.app.appStore.delAppRole.delete(data.id);
      if (res.code == 200){
        let deleteNode = this.$refs.roles.getNode(node);
        this.$refs.roles.remove(deleteNode);
        this.$message.success("操作成功")
      }else{
        this.$alert(res.msg, "提示", {type: 'error'})
      }
    },
    // 移除用户
    async removeMember(row, index){
      var res = await this.$API.app.appStore.deleteAppRoleUser.delete(row.id);
      if (res.code == 200) {
        this.getUsers(this.roleId);
        this.$message.success("删除成功")
      } else {
        this.$alert(res.msg, "提示", { type: "error" })
      }
    },
    // 批量移除用户
    batchMemberDel(){
      this.$confirm(`确定要删除选中的 ${this.selection.length} 项吗？删除后数据不可被恢复。`, "提示", {
        type: "warning"
      })
        .then(async () => {
          let ids = this.selection.map((item) => item.id)
          var res = await this.$API.app.appStore.deleteAppRoleUser.delete(ids)
          if (res.code == 200) {
            this.getUsers(this.roleId);
            this.$message.success("操作成功")
          } else {
            this.$alert(res.msg, "提示", { type: "error" })
          }
          const loading = this.$loading()
          loading.close()
        })
        .catch(() => {})
    },
    // 选择用户
    selectUser(){
      this.dialog.select = true;
      this.$nextTick(() => {
        this.$refs.selectDialog.open(this.roleId, 'approle',this.appId);
      })
    },
    // 会员搜索
    memberSearch() {
      this.params.searchValue = this.search.keyword;
      this.getUsers(this.roleId);
    },
    //表格选择后回调事件
    selectionChange(selection) {
      this.selection = selection
    },
    //本地更新数据
    handleSaveSuccess() {
      this.getUsers(this.roleId);
    },
  },
}
</script>

<style lang="scss" scoped>
.menu:deep(.el-tree-node__label) {display: flex;flex: 1;height:100%;}
.custom-tree-node {display: flex;flex: 1;align-items: center;justify-content: space-between;font-size: 14px;padding-right: 24px;height:100%;}
.custom-tree-node .code {font-size: 12px;color: #999;}
.custom-tree-node .do {display: none;}
.custom-tree-node:hover {color: #409eff;}
.custom-tree-node:hover .code {display: none;}
.custom-tree-node:hover .do {display: inline-block;animation: fadeIn;animation-duration: 1s;}
.custom-tree-node.disabled{text-decoration:line-through; color: #aaa;}
.custom-tree-node.disabled .code {font-size: 12px;color: #aaa;}
</style>
